import {
  delUserChannelAPI,
  getAllChannelAPI,
  getUserChannelAPI,
  setUserChannelAPI,
} from '@/api/channel';
import { getLocalChannels, hasToken, setLocalChannels } from '@/utils/storage';
import { AppDispatch } from '../reducer';
import { channelActionType, channelListType } from '../reducer/channel';

/** 获取所有的频道Action */
export const getAllChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    const res = await getAllChannelAPI();
    dispatch({ type: 'channel/saveChannel', payload: res.data.channels });
  };
};

/** 获取用户的频道Action */
export const getUserChannelAction = () => {
  return async (dispatch: AppDispatch) => {
    // 判断有没有登录,设置userChannelList
    if (hasToken()) {
      const res = await getUserChannelAPI();
      // console.log(res);
      dispatch({ type: 'channel/saveUserChannel', payload: res.data.channels });
    } else {
      // 没有Token,就从本地获取频道
      const localList = getLocalChannels();
      // 判断频道是否为空
      if (localList.length) {
        dispatch({ type: 'channel/saveUserChannel', payload: localList });
      } else {
        // 为空则重新发送请求
        const res = await getAllChannelAPI();
        // 只显示10条频道(截取10条数据)
        const localList = res.data.channels.slice(0, 10);
        // 保存到本地
        setLocalChannels(localList);
        // 保存到reducer
        dispatch({
          type: 'channel/saveUserChannel',
          payload: localList,
        });
      }
    }
  };
};

/** 设置用户的频道Action */
export const setUserChannelAction = (newItem: channelListType) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await setUserChannelAPI({ channels: [newItem] });
      console.log(res);
      dispatch({
        type: 'channel/updateUserChannel',
        payload: newItem,
      });
      return;
    }
    // 未登录时也能操作频道(新增频道)
    const localList = getLocalChannels();
    setLocalChannels([...localList, newItem]);
    dispatch({
      type: 'channel/updateUserChannel',
      payload: newItem,
    });
  };
};

/** 删除指定用户的频道Action */
export const delUserChannelAction = (id: number) => {
  return async (dispatch: AppDispatch) => {
    if (hasToken()) {
      const res = await delUserChannelAPI(id);
      console.log(res);
      dispatch({ type: 'channel/delUserChannel', payload: id });
      return;
    }
    // 未登录时也能操作频道(删除频道)
    const localList = getLocalChannels().filter((item) => item.id !== id);
    setLocalChannels([...localList]);
    dispatch({ type: 'channel/delUserChannel', payload: id });
  };
};

/** 设置修改tab栏的状态的channel_Id的Action */
export const setChannel_IdAction = (channel_Id: number): channelActionType => {
  return {
    type: 'channel/setChannel_Id',
    payload: channel_Id,
  };
};
